package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.bean.user.UserObject;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowBottomDialog;
import com.lishe.lishe.lishe.module.excitation.presenter.ExcitationPresenter;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.CameraUtils;
import com.lishe.lishe.lishe.utils.FileUtils;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.PermissionUtils;
import com.lishe.lishe.retrofit.BaseRequestBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.MyObserver.FileUploadObserver;
import com.lishe.lishe.retrofit.bean.UploadInfo;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;

/**
 * Created by yang on 2017/11/21.
 */

public class PersonModifyHeadActivity extends BaseActivity implements View.OnClickListener {

    public static final void jump(Activity activity, UserObject user) {
        Intent intent = new Intent(activity, PersonModifyHeadActivity.class);
        mUserObject = user;
        activity.startActivityForResult(intent, PersonMessageModifyActivity.REQUEST_CODE_MODIFY_HEAD);
    }

    public static final void jump(Activity activity, String userAvatarPath) {
        Intent intent = new Intent(activity, PersonModifyHeadActivity.class);
        if (mUserObject == null) {
            mUserObject = new UserObject();
        }
        mUserObject.setUserAvatarPath(userAvatarPath);
        activity.startActivityForResult(intent, PersonMessageModifyActivity.REQUEST_CODE_MODIFY_HEAD);
    }

    private TextView mTextTitle;
    private Button mButtonBack;
    private ImageView mImageHead, mImageMore;

    private File mImageFilePath;
    private boolean mIsNull = false;
    private ShowBottomDialog.Builder builder = null;
    private static UserObject mUserObject;
    private ImageLoaderUtils mImageLoaderUtils;
    private int OpenSDCart = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_modify_head);
        mImageLoaderUtils = new ImageLoaderUtils();
        initView();
        setListener();
    }

    private void initView() {
        mTextTitle = findViewById(R.id.title_text_title);
        mButtonBack = findViewById(R.id.title_left_button);
        mImageMore = findViewById(R.id.title_rigth_image);
        mImageHead = findViewById(R.id.head);

        mTextTitle.setText(R.string.person_head);
        mImageMore.setVisibility(View.VISIBLE);
        mImageMore.setImageResource(R.mipmap.more_icon);
        if (!TextUtils.isEmpty(mUserObject.getUserAvatarPath())) {
            mImageLoaderUtils.displayImage(mUserObject.getUserAvatarPath(), mImageHead);
        }
    }

    private void updateHeadImage(Bitmap bmp) {
        mImageHead.setImageBitmap(bmp);
    }

    private void setListener() {
        mButtonBack.setOnClickListener(this);
        mImageMore.setOnClickListener(this);
        mImageHead.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showBottomDialog();
                return false;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CameraUtils.REQUEST_OPEN_CAMERA) {
                //打开相机拍照不保存、不裁剪
                Bitmap bmp = (Bitmap) data.getExtras().get("data");
                updateHeadImage(bmp);

                //根据图片流上传文件
                byte[] buff = BitmapUtils.BitmapToByte(bmp);
                try {
                    ExcitationPresenter.getInstance().updateUserInfo(buff, Globals.getToken(), mUserObject, listener);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    toast(getString(R.string.data_parse_fail));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == CameraUtils.OPEN_ALBUM) {
                String filePath = null;
                //打开系统图库后的回调
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    filePath = CameraUtils.handlerImageOnKitKat(data, PersonModifyHeadActivity.this);
                } else {
                    filePath = CameraUtils.getImagePath(data.getData(), null, PersonModifyHeadActivity.this);
                }
                mImageFilePath = new File(filePath);
                Uri uri = Uri.fromFile(mImageFilePath);
                CameraUtils.getClipPhotoByPickPicture(uri, PersonModifyHeadActivity.this);
            } else if (requestCode == CameraUtils.CLIP_PHOTO_PICTURE) {
                //裁剪后的返回
                Bitmap bmp = BitmapFactory.decodeFile(FileUtils.getClipPhotoByPickPicturePath(PersonModifyHeadActivity.this).getAbsolutePath());
                updateHeadImage(bmp);

                //图片裁剪后开始上传
                uploadFile(FileUtils.getClipPhotoByPickPicturePath(PersonModifyHeadActivity.this));

            } else if (requestCode == CameraUtils.REQUEST_OPEN_CAMERA_AND_SAVE) {
                //打开相机拍照保存并上传
                if (data == null) {
                    //data为空
                    Log.e("TAG", "onActivityResult  requestCode = " + requestCode + ",intent 为 null");
                    if (mIsNull) {
                        Uri uri = Uri.fromFile(mImageFilePath);
                        mIsNull = false;

                        updateHeadImage(ImageLoader.getInstance().loadImageSync(uri.toString()));

//                        CameraUtils.getClipPhotoByPickPicture(uri, PersonModifyHeadActivity.this);//裁剪功能暂不需要

                        uploadFile(mImageFilePath);
                        CameraUtils.ScannerByReceiver(context, mImageFilePath.getAbsolutePath());
                    }
                }

            }
        }
    }

    private void uploadFile(File file) {
        //开始上传图片并更新用户信息
        if (file.exists()) {
            try {
                //文件上传还有更新用户头像信息
                ExcitationPresenter.getInstance().updateUserInfo(file, Globals.getToken(), mUserObject, listener);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                toast(getString(R.string.data_parse_fail));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onBackPressed() {
        Back();
    }

    private void Back() {
        setResult(RESULT_OK, null);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                Back();
                break;
            case R.id.title_rigth_image:
                showBottomDialog();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        /**
         * grantResults 返回-1，表示请求权限失败，返回0表示请求权限成功
         */
        boolean success = true;
        for (int i : grantResults) {
            if (i != 0) {
                success = false;
                break;
            }
        }
        if (success) {
            if (requestCode == PermissionUtils.request_permission_camera) {
                //打开相机拍照不保存
//            CameraUtils.openCamera(PersonModifyHeadActivity.this);
                //打开相机拍照并保存
                if (mImageFilePath == null) mImageFilePath = FileUtils.getLSDir();
                CameraUtils.openCamera(PersonModifyHeadActivity.this, mImageFilePath);
            } else if (requestCode == PermissionUtils.request_WRITE_EXTERNAL_STORAGE) {
                if (OpenSDCart == 1) {
                    CameraUtils.openAlbum(PersonModifyHeadActivity.this);
                } else if (OpenSDCart == 2) {
                    saveBitmap();
                }
            }
        } else {
            toast(getString(R.string.get_sdcard_permission_fail_please_to_get_permission_for_setting));
        }
    }

    private void showBottomDialog() {
        if (builder == null) {
            builder = new ShowBottomDialog.Builder(PersonModifyHeadActivity.this);
            View view = getLayoutInflater().inflate(R.layout.dialog_person_mofify_head, null);
            builder.setContentView(view);

            TextView picture = view.findViewById(R.id.picture);
            TextView select = view.findViewById(R.id.select);
            TextView save = view.findViewById(R.id.save);
            TextView dismiss = view.findViewById(R.id.dismiss);

            picture.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //打开相机拍照并保存到相册
                    mIsNull = true;
                    mImageFilePath = FileUtils.getLSDir();
                    if (PermissionUtils.isCameraAndWriteExternalStoragePermission(PersonModifyHeadActivity.this)) {
                        CameraUtils.openCamera(PersonModifyHeadActivity.this, mImageFilePath);
                    }
//                    if (PermissionUtils.isCameraPermission(PersonModifyHeadActivity.this)) {
//                        //打开相机拍照不保存，返回的bitmap分辨率太低
//                        CameraUtils.openCamera(PersonModifyHeadActivity.this);
//                    }

                    builder.dissmiss();
                }
            });
            select.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (PermissionUtils.isStorageWritePermission(PersonModifyHeadActivity.this)) {
                        OpenSDCart = 1;
                        CameraUtils.openAlbum(PersonModifyHeadActivity.this);
                    }
                    builder.dissmiss();
                }
            });
            save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.dissmiss();
                    saveBitmap();
                }
            });

            dismiss.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.dissmiss();
                }
            });
        }
        builder.show();
    }

    private void saveBitmap() {
        BitmapDrawable drawable = (BitmapDrawable) mImageHead.getDrawable();
        Bitmap bmp = drawable.getBitmap();
        if (PermissionUtils.isStorageWritePermission(PersonModifyHeadActivity.this)) {
            OpenSDCart = 2;
            File file = FileUtils.getLSDir();
            if (BitmapUtils.saveBitmap(bmp, file)) {
                toast(R.string.save_success);
                CameraUtils.ScannerByReceiver(context, file.getAbsolutePath());
            } else {
                toast(R.string.save_file_fail_and_no_sdcard_permission);
            }
        }
    }

    private DataResponseListener<String> listener = new DataResponseListener<String>() {
        @Override
        public void onSuccess(String userAcatarPath) {
            Log.e("TAG", "  onSuccess  ");
            mUserObject.setUserAvatarPath(userAcatarPath);
        }

        @Override
        public void onFail(String failMessage) {
            toast(failMessage);
        }

        @Override
        public void onError(Throwable e) {
            Log.e("TAG", "  onError  =" + e.toString());
        }

        @Override
        public void onPrepare() {
            super.onPrepare();
            LoadingUtils.createLoadingDialog(PersonModifyHeadActivity.this, "正在上传...", false);
        }

        @Override
        public void onUploadFail(String failMessage) {
            Log.e("TAG", "  onUpLoadFail  =" + failMessage);
            LoadingUtils.closeDialog();
            toast("上传失败！");
        }

        @Override
        public void onUploadSuccess() {
            Log.e("TAG", "  onUpLoadSuccess  ");

            LoadingUtils.closeDialog();
            toast("上传成功！");
        }
    };
}
